package com.lbt.writing.controller;

import com.lbt.writing.common.Result;
import com.lbt.writing.dto.User;
import com.lbt.writing.service.UserService;
import com.lbt.writing.utils.JWTUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@Api(tags = "用户接口")
@RestController
@RequestMapping("/api/user")
public class UserController {

    @Autowired
    private UserService userService;

    // 登录功能
    @ApiOperation(value = "用户登录", notes = "根据用户名和密码登录，返回 JWT 令牌")
    @PostMapping("/login")
    public Result<String> login(@RequestParam String username, @RequestParam String password, @RequestParam(defaultValue = "false") boolean remember) {
        // 验证用户名和密码
        User user = userService.getByUsername(username);
        if (user == null || !user.getPassword().equals(password)) {
            return Result.error(401,"登陆失败，账户名或密码错误");
        }

        // 生成 JWT 令牌
        String token = JWTUtils.createToken(username, remember);

        return Result.success("登录成功", token);
    }
}
